// pages/profile/profile.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isLoggedIn: false,
    userInfo: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.checkLoginStatus();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 每次显示页面时检查登录状态
    this.checkLoginStatus();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},

  checkLoginStatus() {
    const token = wx.getStorageSync("token");
    const userInfo = wx.getStorageSync("userInfo");

    this.setData({
      isLoggedIn: !!token,
      userInfo: userInfo || null,
    });
  },

  navigateToLogin() {
    wx.navigateTo({
      url: "/pages/login/login",
    });
  },

  navigateToOrders() {
    if (!this.data.isLoggedIn) {
      this.checkLogin();
      return;
    }
    wx.navigateTo({
      url: "/pages/order/list",
    });
  },

  navigateToFavorites() {
    if (!this.data.isLoggedIn) {
      this.checkLogin();
      return;
    }
    wx.navigateTo({
      url: "/pages/favorite/list",
    });
  },

  navigateToAddress() {
    if (!this.data.isLoggedIn) {
      this.checkLogin();
      return;
    }
    wx.navigateTo({
      url: "/pages/address/list",
    });
  },

  navigateToNutrition() {
    if (!this.data.isLoggedIn) {
      this.checkLogin();
      return;
    }
    wx.navigateTo({
      url: "/pages/nutrition/analysis",
    });
  },

  navigateToFeedback() {
    wx.navigateTo({
      url: "/pages/feedback/feedback",
    });
  },

  navigateToSettings() {
    wx.navigateTo({
      url: "/pages/settings/settings",
    });
  },

  checkLogin() {
    wx.showModal({
      title: "提示",
      content: "请先登录",
      success: (res) => {
        if (res.confirm) {
          this.navigateToLogin();
        }
      },
    });
  },

  handleLogout() {
    wx.showModal({
      title: "提示",
      content: "确定要退出登录吗？",
      success: (res) => {
        if (res.confirm) {
          // 清除登录状态
          wx.removeStorageSync("token");
          wx.removeStorageSync("userInfo");

          this.setData({
            isLoggedIn: false,
            userInfo: null,
          });

          wx.showToast({
            title: "已退出登录",
            icon: "success",
          });
        }
      },
    });
  },
});
